package com.iwechat.controller;

import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSONObject;
import com.iwechat.emuns.ConstEmus;

/**
 * 模拟微信服务器
 */
@Controller
@RequestMapping("/tm")
public class WxTemplateMsgServerController {

    private static final Logger logger = LogManager.getLogger();

    /**
     * 模拟微信端 - 单条模板消息
     */
    @RequestMapping(value = "/wx", method = { RequestMethod.GET, RequestMethod.POST })
    public void singleMessage(HttpServletRequest request, HttpServletResponse response) {
        try {
            InputStream inStream = null;
            inStream = request.getInputStream();
            response.setCharacterEncoding(request.getCharacterEncoding());
            String query = IOUtils.toString(inStream, request.getCharacterEncoding());
            logger.info("wx recive message length: " + query.length());

            JSONObject ret = new JSONObject();
            ret.put(ConstEmus.errorCode.value(), 0);
            ret.put(ConstEmus.errorMesg.value(), "echo req length==>" + query.length());

            response.setCharacterEncoding(response.getCharacterEncoding());
            response.setContentType("text/json;charset=" + response.getCharacterEncoding());
            PrintWriter write = response.getWriter();
            String s = ret.toJSONString();
            logger.info("wx response message : " + s);
            write.println(s);
        } catch (Exception e) {
            logger.error(e, e);
        }
    }
}
